public class Main {
    /**
     * 替换空格
     * https://leetcode.cn/problems/ti-huan-kong-ge-lcof/
     * 请实现一个函数，把字符串 s 中的每个空格替换成"%20"。
     */
    public static void main(String[] args) {
        System.out.println("hello world 0_<");
        String s = "We are happy.";
//        String result = "We%20are%20happy.";
        System.out.println(new Main().replaceSpace(s));
    }
    public String replaceSpace(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' '){
                str.append("  ");
            }
        }
        if (str.length() == 0) {
            return s;
        }

        int left = s.length() - 1;
        int right = left + str.length();
        s += str.toString();
        char[] result = s.toCharArray();
        while (left >= 0) {
            if (result[left] == ' ') {
                result[right--] = '0';
                result[right--] = '2';
                result[right--] = '%';
            }
            else {
                result[right--] = result[left];
            }
            left--;
        }

        return new String(result);
    }
}
